package common.impl;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

import common.interf.IServletHandle;


public class ServletHandleImpl implements IServletHandle{
	/**
	 * 写回 client（不含success）
	 * @param	res response
	 * 			msgs 要回写的消息
	 */
	public int writeToClient(HttpServletResponse res, String msgs){
		if(null == msgs)
			msgs="";
		res.setContentType("text/html;charset=UTF-8");
		res.addHeader("Cache-Control", "no-cache");
		try{
	    	PrintWriter out = res.getWriter();
			out.write(msgs);
			out.flush();
			out.close();
	    } catch (Exception e){
	    	e.printStackTrace();
	    }
	    return 1;
	}
	
	/**
	 * 写回client
	 * @param res
	 * @param msgs
	 * @param type
	 * @return
	 */
	public int writeToClient(HttpServletResponse res,String msgs,String type){
		if(null==msgs)
			msgs="";
		res.setContentType("text/html; charset=UTF-8");
		if(type.trim().toLowerCase().equals("xml"))
			res.setContentType("text/XML;charset=utf-8");
		if("jsonp".equals(type))
			msgs = "callback(" + msgs + ")";
		else
			res.addHeader("Cache-Control", "no-cache");
		try{
	    	PrintWriter out = res.getWriter();
			out.write(msgs);
			out.flush();
			out.close();
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	    return 1;
	}
	/**
	 * 写回client（含success）
	 * @param res
	 * @param msgs
	 * @return
	 */
	public int writeToClient1(HttpServletResponse res,String msgs){
		if(null == msgs)
			msgs="";
		res.setContentType("text/html;charset=UTF-8");
		res.addHeader("Cache-Control", "no-cache");
		JSONObject jobj = new JSONObject();
		if(msgs.indexOf("{\"errors")==0 || msgs.indexOf("{\"msgs")==0)
			jobj.put("success", false);
		else
			jobj.put("success", true);
		jobj.put("result", msgs);
		try{
	    	PrintWriter out = res.getWriter();
			out.write(jobj.toString());
			out.flush();
			out.close();
	    }catch(Exception e){}
	    return 1;
	}
	/**
	 * 写向client
	 * @param	res resonse对象
	 * 			jobj json对象
	 */
	public int writeToClient(HttpServletResponse res,JSONObject jobj){
		if(null == jobj || jobj.isEmpty())
			return 0;
		res.setContentType("text/html; charset=UTF-8");
		try{
	    	//res.getWriter().print("{result:0,msgs:" + jobj.toString() + "}");
			String s = "{result:0,msgs:" + jobj.toString() + "}";
			PrintWriter out = res.getWriter();
			out.write(s);
			out.flush();
			out.close();
	    }catch(Exception e){}
	    return 1;
	}
	
	public String getServerPath(HttpServletRequest request){
		return request.getScheme() + "://" + request.getServerName() + ":" + 
		request.getServerPort() + request.getContextPath();
	}
	
}
